package cn.jinjimi.app.main.activity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.event.PhotoInfoEvent;
import cn.jinjimi.app.entity.PictureShow;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.extend.BaseActivity;
import cn.jinjimi.app.main.widget.FrescoImageView.FrescoImageView;
import cn.jinjimi.app.main.widget.MyProgress;
import cn.jinjimi.app.main.widget.MyViewPager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
import uk.co.senab.photoview.more.ImageDownloadListener;

public class PhotoPreviewActivity extends BaseActivity implements View.OnClickListener {

    List<PictureShow> pictureShowList = new ArrayList<PictureShow>();
    public int index = 0;

    public MyViewPager mViewPager;
    private PhotoAdapter mAdapter;
    private TextView tvPhotoNum;

    private RelativeLayout rlHead;

    private AnimatorSet animatorSet;

    @Override
    protected void beforeInitView() {
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
        setContentView(R.layout.activity_photo_preview);
        initPictureData();
        setSwipeEnabled(false);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
    }

    protected void initView() {
        mViewPager = (MyViewPager) findViewById(R.id.view_pager);
        tvPhotoNum = (TextView) findViewById(R.id.tv_photo_guide);
        rlHead = (RelativeLayout) findViewById(R.id.layout);

        resetHeadView();
        initUnderView();
        initAdapter();
        initAnimation();
    }

    /* 重设标题栏高度 */
    private void resetHeadView() {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rlHead.getLayoutParams();
        layoutParams.setMargins(0, AndroidUtils.getStatusBarHeight(this), 0, 0);
        rlHead.setLayoutParams(layoutParams);
    }

    /* 初始化下标 */
    public void initUnderView() {
        if (pictureShowList.size() == 1) {
            tvPhotoNum.setVisibility(View.GONE);
        } else {
            tvPhotoNum.setVisibility(View.VISIBLE);
            tvPhotoNum.setText(String.format(getString(R.string.img_current_chose_num), index + 1, pictureShowList.size()));
        }
    }

    public void initAdapter() {
        mAdapter = new PhotoAdapter(this);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setDrawingCacheEnabled(true);
        mViewPager.setCurrentItem(index);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setPhotoNum();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    /* 设置底部提醒数字 */
    private void setPhotoNum() {
        if (pictureShowList.size() > 1) {
            tvPhotoNum.setText(String.format(getString(R.string.img_guide_num), mViewPager.getCurrentItem() + 1, pictureShowList.size()));
        }
    }

    private void initAnimation() {
        animatorSet = new AnimatorSet();
        animatorSet.setDuration(300);
        animatorSet.setInterpolator(new AccelerateInterpolator());
    }

    protected void initListener() {
        findViewById(R.id.img_back).setOnClickListener(this);
        findViewById(R.id.txt_delete).setOnClickListener(this);
    }

    public void initPictureData() {
        List<PictureShow> picShowList = (List<PictureShow>) getIntent().getSerializableExtra(BundleKey.PARAM_PICTURE_SHOW);
        index = getIntent().getIntExtra(BundleKey.PARAM_START_INDEX, 0);
        pictureShowList.addAll(picShowList);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                onBackPressed();
                break;
            case R.id.txt_delete:
                cancelEditAlert();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        exitPhotoPreview();
        super.onBackPressed();
    }

    private void exitPhotoPreview() {
        PhotoInfoEvent photoInfoEvent = new PhotoInfoEvent();
        photoInfoEvent.state = PhotoInfoEvent.BACK;
        EventBus.getDefault().post(photoInfoEvent);
    }

    public void cancelEditAlert() {
        getAlertDialog().setTitle(getString(R.string.delete))
                .setMessage(getString(R.string.insure_delete_photos))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();

                        PhotoInfoEvent photoInfoEvent = new PhotoInfoEvent();
                        photoInfoEvent.state = PhotoInfoEvent.DELETE;
                        PhotoInfoEvent.position = mViewPager.getCurrentItem();
                        photoInfoEvent.id = String.valueOf(pictureShowList.get(mViewPager.getCurrentItem()).getId());
                        EventBus.getDefault().post(photoInfoEvent);

                        pictureShowList.remove(mViewPager.getCurrentItem());
                        if (pictureShowList.size() == 1) {
                            tvPhotoNum.setVisibility(View.GONE);
                        }
                        if (pictureShowList.size() == 0) {
                            finish();
                        }

                        setPhotoNum();
                        mAdapter.notifyDataSetChanged();
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    class PhotoAdapter extends PagerAdapter {
        private Context mContext;

        PhotoAdapter(Context context) {
            mContext = context;
        }

        @Override
        public int getCount() {
            return pictureShowList.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            final PictureShow pictureShow = pictureShowList.get(position);
            View cell = LayoutInflater.from(mContext).inflate(R.layout.normal_photo_browser_item_view, null);
            final ViewHolder holder = new ViewHolder();

            holder.photoView = (PhotoView) cell.findViewById(R.id.photo_view);
            holder.frescoView = (FrescoImageView) cell.findViewById(R.id.fresco_view);
            holder.progress_bar = (MyProgress) cell.findViewById(R.id.progress_bar);
            holder.progress_bar.setVisibility(View.GONE);

            holder.photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    if (hasShowBar)
                        hidTitleBar();
                    else
                        showTitlebar();
                }
            });

            holder.photoView.setImageDownloadListener(new ImageDownloadListener() {
                @Override
                public void onUpdate(int progress) {
                    if (progress >= 100) {
                        holder.progress_bar.setVisibility(View.GONE);
                    } else {
                        holder.progress_bar.setVisibility(View.VISIBLE);
                    }
                    holder.progress_bar.setProgress(progress);
                }
            });

            if (StringUtils.isNotEmpty(pictureShow.bigUrl)) {
                if (pictureShow.bigUrl.endsWith(".gif")) {
                    holder.photoView.setVisibility(View.GONE);
                    holder.frescoView.setVisibility(View.VISIBLE);
                    holder.frescoView.loadLocalImage(pictureShow.bigUrl);
                } else {
                    holder.frescoView.setVisibility(View.GONE);
                    holder.photoView.setVisibility(View.VISIBLE);
                    holder.photoView.setImageUri(pictureShow.bigUrl);
                }
            }
            container.addView(cell, AndroidUtils.getWindowWidth(PhotoPreviewActivity.this), AndroidUtils.getWindowHeight(PhotoPreviewActivity.this));

            return cell;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }

    public class ViewHolder {
        PhotoView photoView;
        FrescoImageView frescoView;
        MyProgress progress_bar;
    }

    private boolean hasShowBar = true;

    /* 展示标题栏 */
    private void showTitlebar() {
        if (animatorSet.isRunning())
            return;
        animatorSet.removeAllListeners();
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(rlHead, "alpha", 0, 1),
                ObjectAnimator.ofFloat(rlHead, "translationY", -rlHead.getHeight(), 0),
                ObjectAnimator.ofFloat(tvPhotoNum, "translationY", (tvPhotoNum.getHeight() + getResources().getDimension(R.dimen.dp_20)), 0)

        );
        animatorSet.setStartDelay(200);
        animatorSet.start();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        hasShowBar = true;
    }

    /* 隐藏标题栏 */
    private void hidTitleBar() {
        if (animatorSet.isRunning())
            return;
        animatorSet.removeAllListeners();
        animatorSet.setStartDelay(0);
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(rlHead, "alpha", 1, 0),
                ObjectAnimator.ofFloat(rlHead, "translationY", 0, -rlHead.getHeight()),
                ObjectAnimator.ofFloat(tvPhotoNum, "translationY", 0, (tvPhotoNum.getHeight() + getResources().getDimension(R.dimen.dp_20)))

        );
        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        animatorSet.start();
        hasShowBar = false;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.activity_fade_out);
    }
}
